package com.pmt.feedplayer.platform

import com.pmt.feedplayer.data.PlaybackState
import com.pmt.feedplayer.data.PlaybackProgress
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import platform.AVFoundation.*
import platform.Foundation.*
import platform.UIKit.UIView

/**
 * iOS 平台的 Player 实现，使用 AVPlayer
 */
actual class PlayerImpl : Player {
    private var avPlayer: AVPlayer? = null
    private var playerLayer: AVPlayerLayer? = null
    private var playerView: UIView? = null
    private var timeObserver: Any? = null
    
    private val _playbackStateFlow = MutableStateFlow(PlaybackState.IDLE)
    private val _progressFlow = MutableStateFlow(PlaybackProgress(0, 0, 0))
    private val _errorFlow = MutableSharedFlow<String>()
    
    override val playbackStateFlow = _playbackStateFlow.asStateFlow()
    override val progressFlow = _progressFlow.asStateFlow()
    override val errorFlow = _errorFlow.asSharedFlow()
    
    init {
        initializePlayer()
    }
    
    private fun initializePlayer() {
        avPlayer = AVPlayer()
        setupTimeObserver()
    }
    
    private fun setupTimeObserver() {
        avPlayer?.let {\ player ->
            // 设置时间观察者，每秒更新一次进度
            val timeScale = CMTimeScale(NSEC_PER_SEC.toLong())
            val time = CMTimeMakeWithSeconds(1.0, timeScale)
            
            timeObserver = player.addPeriodicTimeObserverForInterval(
                interval = time,
                queue = null
            ) { time ->
                updateProgress(time)
            }
        }
    }
    
    private fun updateProgress(time: CMTime) {
        avPlayer?.let {\ player ->
            val currentPosition = CMTimeGetSeconds(time) * 1000 // 转换为毫秒
            val duration = CMTimeGetSeconds(player.currentItem?.duration ?: CMTimeMake(0, 1)) * 1000
            val bufferPosition = player.currentItem?.loadedTimeRanges?.firstOrNull()?.CMTimeRangeValue?.let {\ range ->
                CMTimeGetSeconds(range.start + range.duration) * 1000
            } ?: 0.0
            
            _progressFlow.value = PlaybackProgress(
                currentPosition = currentPosition.toLong(),
                duration = duration.toLong(),
                bufferPosition = bufferPosition.toLong()
            )
        }
    }
    
    override fun setDataSource(url: String) {
        val urlObj = NSURL.URLWithString(url)
        val playerItem = AVPlayerItem.playerItemWithURL(urlObj)
        
        // 设置状态观察
        playerItem.addObserver(
            observer = this,
            keyPath = "status",
            options = NSKeyValueObservingOptionNew,
            context = null
        )
        
        playerItem.addObserver(
            observer = this,
            keyPath = "playbackBufferEmpty",
            options = NSKeyValueObservingOptionNew,
            context = null
        )
        
        playerItem.addObserver(
            observer = this,
            keyPath = "playbackLikelyToKeepUp",
            options = NSKeyValueObservingOptionNew,
            context = null
        )
        
        avPlayer?.replaceCurrentItemWithPlayerItem(playerItem)
        _playbackStateFlow.value = PlaybackState.PREPARING
    }
    
    override fun play() {
        avPlayer?.play()
        _playbackStateFlow.value = PlaybackState.PLAYING
    }
    
    override fun pause() {
        avPlayer?.pause()
        _playbackStateFlow.value = PlaybackState.PAUSED
    }
    
    override fun seekTo(position: Long) {
        avPlayer?.seekToTime(CMTimeMakeWithSeconds(position / 1000.0, CMTimeScale(NSEC_PER_SEC.toLong())))
    }
    
    override fun setVolume(volume: Float) {
        avPlayer?.volume = volume.toDouble()
    }
    
    override fun release() {
        // 移除观察者
        avPlayer?.currentItem?.removeObserver(this, "status")
        avPlayer?.currentItem?.removeObserver(this, "playbackBufferEmpty")
        avPlayer?.currentItem?.removeObserver(this, "playbackLikelyToKeepUp")
        
        // 移除时间观察者
        if (timeObserver != null) {
            avPlayer?.removeTimeObserver(timeObserver)
            timeObserver = null
        }
        
        avPlayer?.pause()
        avPlayer = null
        
        playerLayer?.removeFromSuperlayer()
        playerLayer = null
        
        playerView = null
    }
    
    override fun getPlayerView(): Any? {
        if (playerView == null && avPlayer != null) {
            playerView = UIView()
            playerLayer = AVPlayerLayer.playerLayerWithPlayer(avPlayer)
            playerLayer?.frame = playerView?.bounds ?: CGRectZero
            playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
            playerView?.layer?.addSublayer(playerLayer)
        }
        return playerView
    }
    
    // 处理KVO观察
    fun observeValueForKeyPath(
        keyPath: String?, 
        ofObject: Any?, 
        change: Map<Any?, *>?, 
        context: COpaquePointer?
    ) {
        when (keyPath) {
            "status" -> {
                val status = (ofObject as? AVPlayerItem)?.status
                when (status) {
                    AVPlayerItemStatusReadyToPlay -> {
                        _playbackStateFlow.value = PlaybackState.PLAYING
                        avPlayer?.play()
                    }
                    AVPlayerItemStatusFailed -> {
                        _playbackStateFlow.value = PlaybackState.ERROR
                        val error = (ofObject as AVPlayerItem).error?.localizedDescription ?: "Unknown error"
                        _errorFlow.tryEmit(error)
                    }
                    AVPlayerItemStatusUnknown -> {
                        // 未知状态
                    }
                }
            }
            "playbackBufferEmpty" -> {
                _playbackStateFlow.value = PlaybackState.BUFFERING
            }
            "playbackLikelyToKeepUp" -> {
                val isLikelyToKeepUp = change?.get(NSKeyValueChangeNewKey) as? Boolean ?: false
                if (isLikelyToKeepUp) {
                    _playbackStateFlow.value = PlaybackState.PLAYING
                }
            }
        }
    }
}

/**
 * 创建iOS平台的Player实例
 */
actual fun createPlayer(): Player {
    return PlayerImpl()
}